package sivan.观察者模式;

import com.google.common.cache.*;
import sivan.domain.User;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @Author : xiaowen
 * @create: 2021-03-27 23:37
 */
public class GoogleCacheBuilderDemo {

    private final LoadingCache<String, User> readWriteCacheMap;

    public GoogleCacheBuilderDemo() {
        this.readWriteCacheMap = CacheBuilder.newBuilder().initialCapacity(10000)
                .expireAfterWrite(1, TimeUnit.SECONDS)
                .removalListener((RemovalListener<String, User>) removalNotification ->
                        System.out.println("key = "+removalNotification.getKey()+"被移除了")
                ).build(new CacheLoader<String, User>() {
                    @Override
                    public User load(String s){
                        System.out.println("进入load方法------------------");
                        User user = new User();
                        if (s.equalsIgnoreCase("xiaowen")) {
                            user.setName("xiaowen");
                        } else {
                            user.setName("laishuqing");
                        }
                        return user;
                    }
                });
    }

    public static void main(String[] args) throws Exception {
        GoogleCacheBuilderDemo demo = new GoogleCacheBuilderDemo();
        User user = demo.readWriteCacheMap.get("xiaowen");
        System.out.println("当前对象"+user.toString());
        Thread.sleep(5000);
        System.out.println(demo.readWriteCacheMap);
    }
}
